import 'package:flutter/material.dart';
import '../../utils/log.dart';

//封装图片加载控件，增加图片加载失败时加载默认图片

class HYImageWidget extends StatelessWidget {
  HYImageWidget(
      {@required this.url,
      this.w,
      this.h,
      this.defImagePath = "assets/images/p480747492.jpg"});

  final String url;
  final double w;
  final double h;
  final String defImagePath;

  @override
  Widget build(BuildContext context) {
    Image _image = Image.network(
      url,
      width: w,
      height: h,
      fit: BoxFit.cover,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(ImageStreamListener((_, __) {
      //加载成功
    }, onError: (dynamic exception, StackTrace stackTrace) {
      //加载失败
      hyLog(exception, StackTrace.current);
      // _image = Image.asset(
      //   defImagePath,
      //   width: w,
      //   height: h,
      //   fit: BoxFit.cover,
      // );
    }));
    return _image;
  }
}

class ImageWidget extends StatefulWidget {
  ImageWidget(
      {@required this.url,
      this.w,
      this.h,
      this.defImagePath = "assets/images/p480747492.jpg"});

  final String url;
  final double w;
  final double h;
  final String defImagePath;

  @override
  State<StatefulWidget> createState() => _StateImageWidget();
}

class _StateImageWidget extends State<ImageWidget> {
  Image _image;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _image = Image.network(
      widget.url,
      width: widget.w,
      height: widget.h,
      fit: BoxFit.cover,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(ImageStreamListener((_, __) {
      //加载成功
    }, onError: (dynamic exception, StackTrace stackTrace) {
      //加载失败
      _image = Image.asset(
        widget.defImagePath,
        width: widget.w,
        height: widget.h,
        fit: BoxFit.cover,
      );
    }));
    return _image;
  }
}
